//@ts-nocheck
import React from 'react';
import ReactDOM from 'react-dom';
const rootElement = document.getElementById('root');

/** ↓实际情况react是把组件自己的_state和index放在其自身的虚拟dom上的*/
const _state = []; // → memorizedState
let index = 0; // → 链表

const render = () => {
  index = 0;
  ReactDOM.render(<App/>, rootElement)
};

const myUseState = initialValue => {
  const currentIndex = index;
  _state[currentIndex] = _state[currentIndex] === undefined ? initialValue : _state[currentIndex];
  const setState = newValue => {
    _state[currentIndex] = newValue;
    render()
  };
  index += 1;
  return [_state[currentIndex], setState];
};

function App(){
  const [n, setN] = myUseState(0);
  const [m, setM] = myUseState(0);

  return (
    <div className="App">
      <p>{n}</p>
      <p>
        <button onClick={() => setN(n + 1)}>+1</button>
      </p>
      <p>{m}</p>
      <p>
        <button onClick={() => setM(m + 1)}>+1</button>
      </p>
    </div>
  );
}

ReactDOM.render(<App/>, rootElement);
